import { reqGetCode, reqRegisterUser, reqLogin, reqUserInfo, reqLogout } from "@/api"
export default {
    namespaced: true,
    actions: {
        async getCode({ commit }, phone) {
            let result = await reqGetCode(phone)
            if (result.code == 200) {
                //获取成功后 将验证码放到state中
                commit('GETCODE', result.data)
                return "ok"
            } else {
                return Promise.reject(new Error("faile"))
            }
        },
        //完成注册
        async reqRegisterUser({ commit }, data) {
            let result = await reqRegisterUser(data)
            console.log(result);
            if (result.code == 200) {
                return "ok"
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        async goLogin({ commit }, data) {
            let result = await reqLogin(data)
            if (result.code == 200) {
                // console.log(result);
                // commit('GOLOGIN', result.data.token)
                localStorage.setItem("token", result.data.token)
                commit('GOLOGIN', localStorage.getItem("token"))
                return "ok"
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //获取userInfo存储到state
        async getUserInfo({ commit }) {
            const result = await reqUserInfo()
            if (result.code == 200) {
                commit("GETUSERINFO", result.data)
                return 'ok'
            } else {
                return Promise.reject(new Error('faile'))
            }
        },
        //退出登陆
        async loginOut({ commit }) {
            const result = await reqLogout()
            if (result.code == 200) {
                //清空localStorage的token
                localStorage.removeItem("token")
                //清空仓库中的token 和 userInfo
                commit("ClearAll")
                return "ok"
            } else {
                return Promise.reject(new Error('faile'))
            }
        }
    },
    mutations: {
        GETCODE(state, data) {
            state.myCode = data
        },
        GOLOGIN(state, token) {
            state.token = token
        },
        GETUSERINFO(state, userInfo) {
            state.userInfo = userInfo
        },
        ClearAll(state) {
            state.token = '';
            state.userInfo = {};
        }
    },
    state: {
        myCode: "",
        token: '',
        userInfo: {}
    },
}